package com.topisv.tms.platform.paiu;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillBoxPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillPre;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.platform.furun.StatusVo;
import com.topisv.tms.platform.furun.StockVo;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.rest.entity.Batch;
import com.topisv.tms.rest.vo.AddOrdenoResultPY;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.log.OrderLogService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.service.stock.outstorage.OutstorageBillService;
import com.topisv.tms.service.stock.preinstorage.PreInstorageService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.utils.SystemUtil;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.enums.MDGoodsStatus;
import com.topisv.tms.utils.enums.PYOrderType;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.rule.TMSRule;
import com.topisv.tms.utils.vo.PreInstorageVo;

/**
 * 美丽说接口
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/api/paiu")
public class PaiuRestController {

	@Autowired
	private EdiOrderService ediOrderService;
	
	@Autowired
	private ShopSourceService shopSourceService;
	
	@Autowired
	private CustomersService customerService;
	
	@Autowired
	private PreInstorageService preInstorageService;
	
	@Autowired
	private WorkOrderService workOrderService;
	

	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	
	@Autowired
	private ViewCusStockService viewCusStockService;
	
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private OutstorageBillService outstorageBillService;
	
	private static String keyword = "6659-5e76-ae3e-f927-3f20b950000";
	
	
	@Autowired
	private TMSRule tmsRule;
	
	private static final Logger logger = LoggerFactory.getLogger(PaiuRestController.class);
	

	@RequestMapping(value = "synOrder.py",method = RequestMethod.POST)
	public void create(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		logger.info("同步订单appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
		Customers customers =null;
		try
		{
			jsonRes = new JSONObject();
			jsonRes.put("data", "");
			out = response.getWriter();
			String md5 = SystemUtil.MD5(appkey + data + keyword);
			String base64 = SystemUtil.getBASE64(md5);
			if(!base64.equals(appsecret))
			{
				jsonRes.put("code", 1);
				jsonRes.put("msg", "签名验证失败");
			}
			else
			{
				ShopSource shopSource = null;
				shopSource = shopSourceService.findByHtShopId(appkey+"py");
				
				if(null != shopSource)
				{
					json=JSONObject.fromObject(data);
					
					json = json.getJSONObject("orderInfo");
					EdiOrder e=JsonUtil.getEdiOrderPY(json.toString());
					customers = customerService.findByCustomerCode(shopSource.getCustomerCode());
					if(null == customers)
					{
						jsonRes.put("code", 4);
						jsonRes.put("msg", "客户编码不存在");
					}
					else
					{
						e.setCustomerCode(appkey);
						e.setShopCode(shopSource.getShopCode());
						e.setShopna(shopSource.getShopName());
						e.setErpType(shopSource.getOrdenoSourceCode());
						e.setPlatformCustomerCode(appkey);
						e.setShopId(appkey+"py");
						try {
							
							e=ediOrderService.saveEdiOrderPlat(e);
							if("cancel".equals(e.getStatus())||"no".equals(e.getOrderStatus())){
								jsonRes.put("code", 6);
								jsonRes.put("msg", e.getMessage());
							} else if("repeat".equals(e.getStatus())){
								jsonRes.put("code", 8);
								jsonRes.put("msg", e.getMessage());
							} else
							{
								jsonRes.put("code", "0");
								jsonRes.put("msg","保存成功");
							}
							
						} catch (Exception e1) {
							jsonRes.put("code", 7);
							jsonRes.put("msg", "保存失败");
							logger.error("保存订单失败", e1);
						}
					}
				}
				else
				{
					jsonRes.put("code", 3);
					jsonRes.put("msg", "找不到店铺配置");
				}
			}
			
			try {
				logger.info("同步订单结果=" + jsonRes.toString());
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			
		}
		catch(Exception e)
		{
			jsonRes.put("code", 2);
			jsonRes.put("msg", e.getMessage());
			out.print(jsonRes.toString());
			out.close();
			logger.info("错误==" , e);
		}
	}
	@RequestMapping(value = "synOrderBatch.py",method = RequestMethod.POST)
	public void synOrderBatch(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		JSONObject jsonRes = null;
		PrintWriter out = null;
		logger.info("同步订单appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
		try
		{
			jsonRes = new JSONObject();
			jsonRes.put("data", "");
			out = response.getWriter();
			String md5 = SystemUtil.MD5(appkey + data + keyword);
			String base64 = SystemUtil.getBASE64(md5);
			if(!base64.equals(appsecret))
			{
				jsonRes.put("code", 1);
				jsonRes.put("msg", "签名验证失败");
			}
			else
			{
				ShopSource shopSource = null;
				shopSource = shopSourceService.findByHtShopId(appkey+"py");
				
				if(null != shopSource)
				{
					List<EdiOrder> es=JsonUtil.getEdiOrdersPY(data);
					List<AddOrdenoResultPY> results=new ArrayList<AddOrdenoResultPY>();
					for(int i=0;i<es.size();i++){
						EdiOrder e=es.get(i);
						AddOrdenoResultPY result=new AddOrdenoResultPY();
						result.setOrderCode(e.getCustomerOrdeno());
						e.setCustomerCode(appkey);
						e.setShopCode(shopSource.getShopCode());
						e.setShopna(shopSource.getShopName());
						e.setErpType(shopSource.getOrdenoSourceCode());
						e.setPlatformCustomerCode(appkey);
						e.setShopId(appkey+"py");
						try {
							
							e=ediOrderService.saveEdiOrderPlat(e);
							if("cancel".equals(e.getStatus())||"no".equals(e.getOrderStatus())||"repeat".equals(e.getStatus())){
								result.setStatus("fail");;
								result.setResult(e.getMessage());
							}
							else
							{
								result.setStatus("success");;
								result.setResult("保存成功");
							}
						} catch (Exception e1) {
							result.setStatus("fail");;
							result.setResult(e1.getMessage());
							logger.error("保存订单失败", e1);
						}
						results.add(result);
					}
					
					jsonRes.put("code", "0");
					jsonRes.put("msg", "处理成功");
					jsonRes.put("data", results);
					
				}
				else
				{
					jsonRes.put("code", 3);
					jsonRes.put("msg", "找不到店铺配置");
				}
			}
			
			try {
				logger.info("同步订单结果=" + jsonRes.toString());
				out.print(jsonRes.toString());
				out.close();
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			
		}
		catch(Exception e)
		{
			jsonRes.put("code", 2);
			jsonRes.put("msg", e.getMessage());
			logger.info("同步订单结果=" + jsonRes.toString());
			out.print(jsonRes.toString());
			out.close();
		}
	}
	@RequestMapping(value = "synGoods",method = RequestMethod.POST)
	public void synGoods(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		Batch batch = null;
		logger.info("同步商品jsonData=" + data);
		JSONObject json=null;
		try
		{
			logger.info("同步商品jsonData=" + data);
			
			json=JSONObject.fromObject(data);
			
			json = json.getJSONObject("orderInfo");
			
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "cancelOrder.py",method = RequestMethod.POST)
	public void cancelOrder(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		String orderCode="";
		try
		{
			logger.info("取消订单appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
			String md5 = SystemUtil.MD5(appkey + data + keyword);
			String base64 = SystemUtil.getBASE64(md5);
			jsonRes = new JSONObject();
			jsonRes.put("data", "");
			out = response.getWriter();
			if(!base64.equals(appsecret))
			{
				jsonRes.put("code", 1);
				jsonRes.put("msg", "签名验证失败");
				logger.info("签名验证失败 ");  
			}
			else
			{
				json=JSONObject.fromObject(data);
				
				orderCode = json.getString("orderCode");
				
				String type = json.getString("type");
				
				if("01".equals(type))
				{
					EdiOrder ediOrder = ediOrderService.findByCustomerCodeAndFromno(appkey, orderCode);
					if(ediOrder != null)
					{
						String res = workOrderService.cancelOrder(ediOrder.getOrdeno(),"ADMIN");
						logger.info("取消 ：" + res);  
						if("sended".equals(res))
						{
							jsonRes.put("code", 5);
							jsonRes.put("msg", "已经发货，不能取消");
						}
						else if("cancel".equals(res))
						{
							jsonRes.put("code", "0");
							jsonRes.put("msg", "已经取消");
						}else if("success".equals(res))
						{
							jsonRes.put("code", "0");
							jsonRes.put("msg", "取消成功");
						} 			
					}
					else
					{
						jsonRes.put("code", 2);
						jsonRes.put("msg", "订单号不存在");
					}
				}
				else
				{
					preInstorageService.cancelPreOrderByCusNo(orderCode,appkey);
					jsonRes.put("code", "0");
					jsonRes.put("msg", "取消成功");
				}
			}
			out.print(jsonRes.toString());
			out.close();
		}  catch (PaiUException e) {
				jsonRes.put("code", 4);
				jsonRes.put("msg", e.getMessage());
				out.print(jsonRes.toString());
				out.close();
				logger.error("取消订单("+orderCode+")", e);
		} 	catch(Exception e)	{
			jsonRes.put("code", 3);
			jsonRes.put("msg", e.getMessage());
			out.print(jsonRes.toString());
			out.close();
			logger.error("取消订单("+orderCode+")", e);
		}
		
	}
	
	@RequestMapping(value = "queryStock.py",method = RequestMethod.POST)
	public void queryStock(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		logger.info("查询库存jsonData=" + data);
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		try
		{
			out = response.getWriter();
			jsonRes = new JSONObject();
			json=JSONObject.fromObject(data);
			jsonRes.put("data", "");
			String owner_code = json.getString("customerCode");
			String warehouse = json.getString("warehouseCode");
			String sku = json.getString("sku");
			int pageNum = 1;
			int pageSize = 20;
			try {
				String pageNum_str = json.getString("pageNum");
				String pageSize_Str = json.getString("pageSize");
				if(!"".equals(pageNum_str))
				{
					pageNum = Integer.parseInt(pageNum_str);
				}
				if(!"".equals(pageSize_Str))
				{
					pageSize = Integer.parseInt(pageSize_Str);
				}
			} catch (Exception e) {
			}
			if(!"".equals(sku))
			{
				Page<ViewCusStock> page_sku = this.viewCusStockService.loadViewStock(owner_code,warehouse,sku,"sku",pageNum,pageSize,false);
				if(page_sku.hasContent())
				{
					List<ViewCusStock> content = page_sku.getContent();
					StockVo stockVo = new StockVo();
					for(ViewCusStock viewCusStock : content)
					{
						stockVo.setSku(viewCusStock.getSku());
						stockVo.setNum(viewCusStock.getSalesNum());
						stockVo.setTotal(viewCusStock.getTotalNum());
					}
					jsonRes.put("code", "0");
					jsonRes.put("msg", "success");
					jsonRes.put("num", stockVo.getNum());
					jsonRes.put("total", stockVo.getTotal());
					
				}
				else
				{
					jsonRes.put("code", 1);
					jsonRes.put("msg", "无数据");
				}
			}
			else
			{
				Page<ViewCusStock> page_sku = this.viewCusStockService.loadViewStock(owner_code,warehouse,sku,"sku",pageNum,pageSize);
				if(page_sku.hasContent())
				{
					List<ViewCusStock> content = page_sku.getContent();
					long totalNumber = page_sku.getTotalElements();
					int current =  page_sku.getNumber() + 1;
					int totalPage = page_sku.getTotalPages();
					List<StockVo> list = new ArrayList<StockVo>();
					for(ViewCusStock viewCusStock : content)
					{
						StockVo stockVo = new StockVo();
						stockVo.setSku(viewCusStock.getSku());
						stockVo.setNum(viewCusStock.getSalesNum());
						stockVo.setTotal(viewCusStock.getTotalNum());
						list.add(stockVo);
					}
					jsonRes.put("code", "0");
					jsonRes.put("msg", "success");
					jsonRes.put("totalPage", totalPage);
					jsonRes.put("totalNum", totalNumber);
					jsonRes.put("currentPage", current);
					jsonRes.put("data", list);
				}
				else
				{
					jsonRes.put("code", 1);
					jsonRes.put("msg", "无数据");
				}
			}
			logger.info("库存查询结果=" + jsonRes.toString());
			out.print(jsonRes.toString());
			out.close();

		}
		catch(Exception e)
		{
			jsonRes.put("code", 1);
			jsonRes.put("msg", "error");
			logger.error("查询库存",e);
			out.print(jsonRes.toString());
			out.close();

			return;
		}
		
	}
	
	@RequestMapping(value = "queryOrderStatus.py",method = RequestMethod.POST)
	public void queryOrderStatus(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		try
		{
			logger.info("订单状态jsonData=" + data);
			jsonRes = new JSONObject();
			jsonRes.put("data", "");
			out = response.getWriter();
			json=JSONObject.fromObject(data);
			String order_code = json.getString("orderCode");
			EdiOrder ediOrder = ediOrderService.findByCustomerCodeAndFromno(appkey, order_code);
			if(null != ediOrder)
			{
				List<StatusVo> svoList = new ArrayList<StatusVo>();
				List<OrderLog>  orderLog = orderLogService.loadLogByOrderno(ediOrder.getOrdeno());
				if(null != orderLog && !orderLog.isEmpty())
				{
					for(OrderLog ol : orderLog)
					{
						StatusVo _svo = new StatusVo();
						_svo.setTime(DateUtils.format(ol.getOperateTime(),"yyyy-MM-dd HH:mm:ss"));
						_svo.setContext(ol.getAboutInfo());
						_svo.setStatus(ol.getOperateType());
						svoList.add(_svo);
					}
				}
				jsonRes.put("code", "0");
				jsonRes.put("msg", "success");
				jsonRes.put("data", svoList);
			}
			else
			{
				jsonRes.put("code", 2);
				jsonRes.put("msg", "订单号不存在");
			}
			logger.info("状态查询结果=" + jsonRes.toString());
			out.print(jsonRes.toString());
			out.close();
		}
		catch(Exception e)
		{
			jsonRes.put("code", 1);
			jsonRes.put("msg", e.getMessage());
			out.print(jsonRes.toString());
			out.close();

			return;
		}
		
	}
	
	@RequestMapping(value = "inStore.py",method = RequestMethod.POST)
	public void inStore(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		logger.info("入库jsonData=" + data);
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		try {
			String md5 = SystemUtil.MD5(appkey + data + keyword);
			String base64 = SystemUtil.getBASE64(md5);
			jsonRes = new JSONObject();
			jsonRes.put("data", "");
			out = response.getWriter();

			json=JSONObject.fromObject(data);
			PreInstorageVo preInstorageVo = parseInstorageBill(appkey,json);
			preInstorageService.saveInstorageBillPreLMB(preInstorageVo);;
			jsonRes.put("code", "0");
			jsonRes.put("msg", "成功");
			logger.info("入库结果=" + jsonRes.toString());
			out.print(jsonRes.toString());
			out.close();
		}	catch(Exception e)	{
			jsonRes.put("code", 2);
			jsonRes.put("msg", e.getMessage());
			logger.info("入库结果=" + jsonRes.toString());
			out.print(jsonRes.toString());
			out.close();
			return;
		}
	}
	
	public PreInstorageVo parseInstorageBill(String appkey,JSONObject json) throws Exception
	{
		PreInstorageVo vo = new PreInstorageVo();
		InstorageBillPre instorageBillPre = new InstorageBillPre();
		instorageBillPre.setPreSendTm(TimeUtil.getDateMMSS(json.getString("in_time")));
		instorageBillPre.setCustomerCode(appkey);
		instorageBillPre.setInwarehouseCode(json.getString("warehouse_code"));
		instorageBillPre.setOrderStatus(StatusEnums.PREORDER_STATUS_SEND.getStatus());
		instorageBillPre.setRemark(json.getString("remark"));
		instorageBillPre.setCustomerOrderNo(json.getString("instore_tid"));
		String type = json.getString("type");
		if("01".equals(type))
		{
			instorageBillPre.setBillType(PYOrderType.PRE_ORDER.getType());
			instorageBillPre.setErrorFlg(MDGoodsStatus.NORMAL.getType());
		}
		else if("02".equals(type))
		{
			instorageBillPre.setBillType(PYOrderType.RETURN_ORDER.getType());
			instorageBillPre.setErrorFlg(MDGoodsStatus.OTHERS.getType());
		}
		instorageBillPre.setSubCustomerCode("");
		instorageBillPre.setCusWarehouseCode("");
		instorageBillPre.setOldCusOrderNo("");
		instorageBillPre.setSourceOrdNo(json.getString("source_tid"));
		instorageBillPre.setExpressNo(json.getString("express_tid"));

		List<InstorageBillBoxPre> boxes = new ArrayList<InstorageBillBoxPre>();
		InstorageBillBoxPre box = new InstorageBillBoxPre();
		box.setBoxCode("LMBBOX0001");
		boxes.add(box);
		JSONArray jarray = json.getJSONArray("items");
		List<InstorageBillItemPre> itemPres = new ArrayList<InstorageBillItemPre>();
		for (int i=0;i<jarray.size();i++) {
			JSONObject obj = (JSONObject)jarray.get(i);
			InstorageBillItemPre item = new InstorageBillItemPre();
			EdiGoodsSku ediGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(appkey, obj.getString("bar_code"));
			if(null == ediGoodsSku)
			{
				throw new Exception(obj.getString("bar_code")+"不存在");
			}
			item.setLineNo(ediGoodsSku.getBar());
			item.setSkuCode(obj.getString("bar_code"));
			item.setGoodsNum(obj.getInt("instore_num"));
			item.setBoxCode("LMLMBX0001");
			item.setErrorFlag("other");
			itemPres.add(item);
		}
		vo.setInstorageBillPre(instorageBillPre);
		vo.setInstorageBillBoxPres(boxes);
		vo.setInstorageBillItemPres(itemPres);
		return vo;
	}
	
	@RequestMapping(value = "outStore.py",method = RequestMethod.POST)
	public void outStore(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		logger.info("出库appkey=" + appkey + ",appsecret=" + appsecret + "出库登记jsonData=" + data);
		JSONObject json=null;
		JSONObject jsonRes = null;
		PrintWriter out = null;
		boolean safeCheck =false;
		int code =0;
		try {
			jsonRes = new JSONObject();
			out = response.getWriter();
			String md5 = SystemUtil.MD5(appkey + data + keyword);
			String base64 = SystemUtil.getBASE64(md5);
			if(safeCheck && !base64.equals(appsecret))	{
				jsonRes.put("code", 1);
				jsonRes.put("msg", "签名验证失败");
			} else {
				json=JSONObject.fromObject(data);
				String warehouseCode =  json.getString("warehouseCode");
				if(isBlank(warehouseCode))warehouseCode ="LF";
				String outstoretid = json.getString("outstore_tid");
				String type = json.getString("type");
				if(isBlank(type))type = "return";
				if("01".equalsIgnoreCase(type)){
					type = "return";
				} else if("02".equalsIgnoreCase(type)){
					type = "bad_return";
				} else {
					type = "return";
				}
				JSONArray jarray = json.getJSONArray("items");
				Map<String, Integer> infoMap = new HashMap<String,Integer>();
				for (int i=0;i<jarray.size() && code == 0;i++) {
					JSONObject obj = (JSONObject)jarray.get(i);
					String barCode =  obj.getString("bar_code");
					EdiGoodsSku ediGoodsSku = null;
					if(!isBlank(barCode)){
						 ediGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(appkey,barCode);
					}
					if(null != ediGoodsSku) {
						Integer num = obj.getInt("outstore_num");
						if(null != num && num>0)
							infoMap.put(barCode, num);
					} else {
						logger.error("商家:"+appkey+" SKU:"+barCode+"不存在");
						code = 2;
					}
				}
				StringBuffer sb = new StringBuffer();
				String ret ="";
				if(code ==0){
					ret =outstorageBillService.createBill(appkey, warehouseCode, "",outstoretid, infoMap, type,sb);
					if(!isBlank(ret)){
						code =3;
						logger.warn(appkey+"返厂出库，库存未完成满足，SKU："+ret);
					} 
				}
				jsonRes.put("code", code);
				switch(code){
					case 2:
							jsonRes.put("msg", "SKU不存在");
							break;
					case 3:
							jsonRes.put("msg", "库存不足");
							jsonRes.put("skus",ret);
							break;
				}
				jsonRes.put("billCode", sb.toString());
				logger.info("出库登记=" + jsonRes.toString());
			}
		}	catch(Throwable e)	{
			jsonRes.put("code",4);
			jsonRes.put("msg", e.getMessage());
			logger.error("出库登记异常" ,e);
			return;
		} finally {
			out.print(jsonRes.toString());
			out.close();
		}
	}

	public boolean isBlank(String val){
		return null == val || val.trim().length()==0;
	}
	
	@RequestMapping(value = "synOrder.py",method = RequestMethod.GET)
	public void synOrder2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error("异常：",e);
		}
		
	}
	
	@RequestMapping(value = "cancelOrder.py",method = RequestMethod.GET)
	public void cancelOrder2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error("异常：",e);
		}
		
	}
	
	@RequestMapping(value = "returnGoods.py",method = RequestMethod.GET)
	public void returnGoods2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Throwable e) {
			logger.error("异常：",e);
		}
		
	}
	
	public static void main(String args[]) throws Exception
	{
		String url = "http://ds.alpha.lmbang.com/index.php?c=paiuCallback&a=inStore";
		String appkey = "paiu";
		String keyword = "6659-5e76-ae3e-f927-3f20b950001";
		String data = "{\"items\":[{\"Pro_name\":\"\",\"bar_code\":\"010181040313\",\"pro_sn\":\"CP107922180\",\"instore_num\":\"350\"}],\"instore_tid\":\"YK1077899676707693\",\"warehouse_code\":\"HM\",\"type\":\"1\",\"express_tid\":\"\",\"source_tid\":\"\"}";
		String md5 = SystemUtil.MD5(appkey + data + keyword);
		String appsecret = SystemUtil.getBASE64(md5);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("appkey", appkey));
		nvps.add(new BasicNameValuePair("appsecret", appsecret));
		nvps.add(new BasicNameValuePair("data", data));
		HttpClient httpClient = new DefaultHttpClient();
		org.apache.http.client.methods.HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
		HttpResponse response;
		
		response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200){
			String result = EntityUtils.toString(response.getEntity());
			System.out.println(result);
			
		} else {
			EntityUtils.consume(response.getEntity());
			throw new Exception("response status error: " + response.getStatusLine().getStatusCode());
		}
		
		
	}

}
